<template>
	<view class="publish-content">
		<u-toast ref="uToast"></u-toast>
		<!-- 文本框 -->
		<view class="content-pad">
			<u--textarea 
					v-model="addPostDTO.content" 
					border="none"
					maxlength="1000"
					height="180"
					count
					confirmType="done"
					placeholder="请输入要发布的内容..." >
			</u--textarea>
		</view>
		<!-- 图片上传 -->
		<view class="content-pad">
			<u-upload
				:fileList="fileList"
				@afterRead="afterRead"
				@delete="deletePic"
				name="1"
				accept="image"
				:maxDuration="30"
				multiple
				:maxCount="9"
				uploadIcon="plus"
				uploadText="添加优质首图更加吸引人~"
				width="80"
				height="80"
				:previewFullImage="true"
			></u-upload>
		</view>
		<!-- 线条 -->
		<view><u-line margin="10px" length="95%"></u-line></view>
		<view>
			<u-row 
				justify="space-between"
				gutter="10"
				customStyle="padding: 30rpx 0;margin-left:10rpx">
				<u-col span="3">
					<u-icon label="价格" space="5px" size="20" name="rmb-circle-fill"></u-icon>
				</u-col>
				<u-col span="4" offset="4" justify="end" @click="show=true">
					<view style="font-size: 14px;font-weight: bold;color:red;display: flex; justify-content: flex-end;">
						<text>￥</text>
						<text>{{price}}</text>
					</view>
				</u-col>
				<u-col span="1" @click="show=true">
					<u-icon size="14" name="arrow-right" color="rgb(212,212,212)"></u-icon>
				</u-col>
			</u-row>
			<u-row
				justify="space-between"
				gutter="10"
				customStyle="padding: 30rpx 0;margin-left:10rpx"
				@click="showPicker=true">
				<u-col span="5"><u-icon label="选择所属分类" space="5px" size="20" name="rmb-circle-fill"></u-icon></u-col>
				<u-col span="1" offset="6"><u-icon size="14" name="arrow-right" color="rgb(212,212,212)"></u-icon></u-col>
			</u-row>
			
			<u-picker 
				:closeOnClickOverlay="true"
				:visibleItemCount="5"
				:show="showPicker" 
				:columns="columns" 
				@close="showPicker=false"
				@confirm="confirm"
				keyName="classifyName">
			</u-picker>
		</view>
		
		<!-- 数字键盘 -->
		<u-keyboard ref="uKeyboard" 
			mode="number" 
			@change="valChange" 
			@backspace="backspace"
			:show="show" 
			:tooltip="false" 
			customStyle="background-color:#fff"
			:safeAreaInsetBottom="true" 
			:closeOnClickOverlay="true"
			@close="keyboardClose()">
			<view style="position: relative;top: -100rpx;width: 100%;height: 100rpx;background-color: #d8dadb;">
				<u-row customStyle="padding: 20rpx;border-bottom: 1px solid rgb(202,202,202);">
					<u-col span="2"><u--text text="价格" bold :line="1"></u--text></u-col>
					<u-col span="8">
						<u--input
						    placeholder="￥0.00"
							type="text"
						    border="none"
							@focus="getFocus(0)"
							:value="addPostDTO.amountOfCurrentPrice"
							:focus="true"
							fontSize="18px"
						  ></u--input>
						<!-- <u--text mode="price" :text="addPostDTO.amountOfCurrentPrice" color="rgb(202,202,202)" :line="1"></u--text> -->
					</u-col>
				</u-row>
				<u-row customStyle="padding: 20rpx;border-bottom: 1px solid rgb(202,202,202);">
					<u-col span="2"><u--text text="原价" bold :line="1"></u--text></u-col>
					<u-col span="8">
						<u--input
						    placeholder="￥0.00"
							type="text"
						    border="none"
							@focus="getFocus(1)"
							:value="addPostDTO.amountOfOriginalPrice"
							fontSize="18px"
						  ></u--input>
						<!-- <u--text mode="price" :text="addPostDTO.amountOfOriginalPrice" color="rgb(202,202,202)" :line="1"></u--text> -->
					</u-col>
				</u-row>
			</view>
		</u-keyboard>
		<!-- 发布按钮 -->
		<view style="position: fixed;text-align: center;bottom: 20rpx;width: 100%;">
			<u-button color="#2979ff" @click="submit" customStyle="width: 400rpx;">发布</u-button>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {getClassifyList, getUploadToken, publishDealPost} from '../../utils/api.js'
	export default {
		data() {
			return {
				fileList: [],
				show: false,
				focusIndex: 0,			
				showPicker: false,
				columns: [],
				value: '',
				price: '0.00',
				addPostDTO: {
					content: '',
					imgUrls: '',
					type: 3,
					amountOfCurrentPrice: '',
					amountOfOriginalPrice: '',
					classifyId: 0,
				},
				token: '',
				lookImgPre: '',
			}
		},
		onReady() {
			this.dealClassifyList()
			this.getToken()
		},
		methods: {
			confirm(e){
				this.addPostDTO.classifyId = e.value[0].id
				this.showPicker = false
			},
			dealClassifyList(){
				getClassifyList().then(res => {
					this.columns.push(res)
				})
			},
			getToken(){
				getUploadToken().then(res=>{
					this.token = res.uploadToken
					this.lookImgPre = res.lookImgPre
				})
			},
			keyboardClose(){
				console.log('amountOfCurrentPrice', this.addPostDTO.amountOfCurrentPrice)
				if(this.addPostDTO.amountOfCurrentPrice != ''){
					this.price = this.addPostDTO.amountOfCurrentPrice
				}
				this.show=false
			},
			getFocus(index){
				this.focusIndex = index;
			},
			// 按键被点击(点击退格键不会触发此事件)
			valChange(val) {
				if(this.focusIndex == 0){
					if(this.isNotAdd(this.addPostDTO.amountOfCurrentPrice, val, 0))	return;
					this.addPostDTO.amountOfCurrentPrice += val;
				}else {
					if(this.isNotAdd(this.addPostDTO.amountOfOriginalPrice, val, 1)) return;
					this.addPostDTO.amountOfOriginalPrice += val;
				}
				//console.log(this.addPostDTO.amountOfCurrentPrice);
			},
			isNotAdd(priceStr, val, i){
				//第一次点击为.
				if(priceStr == "" && (val == "." || val == "0")) {
					if(i==0){
						this.addPostDTO.amountOfCurrentPrice = "0.";
					}else {
						this.addPostDTO.amountOfOriginalPrice = "0.";
					}
					return true;
				}
				//解决小数点重复点击以及保留两位小数
				const s = priceStr.substring(priceStr.length-3, priceStr.length-2);
				if(s == "." || (val == "." && priceStr.indexOf(".") != -1)){
					return true;	
				}
			},
			// 键盘退格键被点击
			backspace() {
				// 删除value的最后一个字符
				if(this.focusIndex == 0){
					if(this.addPostDTO.amountOfCurrentPrice.length) this.addPostDTO.amountOfCurrentPrice = this.addPostDTO.amountOfCurrentPrice.substring(0, this.addPostDTO.amountOfCurrentPrice.length - 1);
					if(this.addPostDTO.amountOfCurrentPrice == "0") this.addPostDTO.amountOfCurrentPrice = ""
				}else {
					if(this.addPostDTO.amountOfOriginalPrice.length) this.addPostDTO.amountOfOriginalPrice = this.addPostDTO.amountOfOriginalPrice.substring(0, this.addPostDTO.amountOfOriginalPrice.length - 1);
					if(this.addPostDTO.amountOfOriginalPrice == "0") this.addPostDTO.amountOfOriginalPrice = ""
				}
				
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				const _that = this
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = _that.fileList.length
				//let fileListLen = _that[`fileList${event.name}`].length
				lists.map((item) => {
					_that.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await _that.uploadFilePromise(lists[i].url)
					let item = _that.fileList[fileListLen]
					if(result.hash != null){
						_that.addPostDTO.imgUrls += _that.lookImgPre + result.key + ","
						_that.fileList.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '成功',
							url: _that.lookImgPre + result.key
						}))
						fileListLen++
					}else {
						getApp().globalData.toast[1].message = '图片上传失败!'
						_that.$refs.uToast.show({
							...getApp().globalData.toast[1],
							complete() {
								_that.fileList.splice(i, 1)
							}
						})
					}
					
				}
			},
			uploadFilePromise(url) {
				const that = this
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://upload.qiniup.com/', 
						filePath: url,
						name: 'file',
						timeout: 5000,
						formData: {
							token: that.token,
							//key: url.substr(url.indexOf("0/") + 2)
						},
						success: (res) => {
							resolve(JSON.parse(res.data))
						},
						fail: (error) => {
							console.log("错误!", error)
							resolve(error)
						}
					});
				})
			},
			submit(){
				if(this.addPostDTO.amountOfCurrentPrice == ''){
					getApp().globalData.toast[1].message = '您还没有输入要卖的价格哦!'
					this.$refs.uToast.show({
						...getApp().globalData.toast[1],
						complete() {}
					})

				}else if(this.addPostDTO.classifyId == 0){
					getApp().globalData.toast[1].message = '您还没有选择所属分类哦!'
					this.$refs.uToast.show({
						...getApp().globalData.toast[1],
						complete() {}
					})
				}else {
					let imgs = this.addPostDTO.imgUrls
					if(imgs.length > 1){
						this.addPostDTO.imgUrls = imgs.substr(0, imgs.length - 1)
					}
					publishDealPost(this.addPostDTO).then(res => {
						getApp().globalData.toast[0].message = '商品发布成功!'
						this.$refs.uToast.show({
							...getApp().globalData.toast[0],
							complete() {
								//关闭当前页面重定向
								uni.$u.route({
									type: 'redirect',
									url: 'pages/used-deal/used-deal',
								})
							}
						})
					}).catch(error=>{
						getApp().globalData.toast[1].message = error.message
						this.$refs.uToast.show({
							...getApp().globalData.toast[1],
							complete() {
								uni.$u.route({
									type: 'back',
									delta: 1,
									animationType: 'pop-out',
									animationDuration: 200
								})
							},
						})
					}) 
				}
				
			},
		}
	}
</script>

<style lang="scss" scoped>
	.publish-content{
		.content-pad{
			margin-top: 10rpx; padding: 20rpx;
		}
		
	}
</style>
